package javase0829;

import com.sun.javafx.tk.TKClipboard;

import java.io.*;
import java.net.Socket;
import java.util.*;

public class ServeThread extends Thread{
    private Socket socket;

    public ServeThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            InputStream is = socket.getInputStream();
            OutputStream os = socket.getOutputStream();

            ObjectInputStream ois = new ObjectInputStream(is);
            ObjectOutputStream oos = new ObjectOutputStream(os);
            Object in = ois.readObject();
            Object out = this.out(in);
            oos.writeObject(out);

            oos.close();
            ois.close();
            os.close();
            is.close();
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Object out(Object in) {
        //如果是要登录，验证账号密码，然后结束
        //如果登录状态，进行相应操作（主要业务）
        //如果登录状态不合法，返回信息，要求登录。

        /*
        入参
        //action 干什么？ mes  token身份信息
        Map<String, String> dto = new HashMap<>();
        dto.put("action","");
        dto.put("mes","");
        dto.put("token","");
         */
        Map<String, String> result = new HashMap<>();
        try {
            Map<String, String> dto = (Map<String, String>) in;
            if (LoginServe.LOGIN_ACTION.equals(dto.get("action"))) {
                //账号密码不包含空白、英文逗号。mes 如果是账号密码：账号,密码
                String ap = dto.get("mes");
                String[] aps = ap.split(",");
                String name = aps[0].trim();
                String pwd = aps[1].trim();
                //验证有效性
                String cpwd = LoginServe.aps.get(name);
                if (pwd.equals(cpwd)) {
                    //合法: 显示信息，认证字符串，
                    String token = UUID.randomUUID().toString();
                    LoginServe.tokens.put(token, name);
                    result.put("mes", initIndex());
                    result.put("token", token);
                    result.put("action", "index");
                } else {
                    // 非法
                    //throw new Exception("");
                    /*int[] arr = new int[1];
                    arr[10] = 1;*/
                    int n = 1 / 0;
                }

            } else if (LoginServe.INDEX.equals(dto.get("action"))) {
                check(dto.get("token"));
                if ("1".equals(dto.get("mes"))) {
                    System.out.println(LoginServe.orders);//????
                    result.put("mes", "个人信息："
                            + LoginServe.tokens.get(dto.get("token")) +"\n"
                            + initIndex());
                    result.put("token", dto.get("token"));
                    result.put("action", "index");
                } else if ("0".equals(dto.get("mes"))) {
                    LoginServe.tokens.remove(dto.get("token"));
                    result.put("mes", "退出成功\n请输入登录信息，账号密码之间用英文逗号分隔：");
                    result.put("token", dto.get("token"));
                    result.put("action", "login");
                } else if ("2".equals(dto.get("mes"))) {

                    result.put("mes", initOrder());
                    result.put("token", dto.get("token"));
                    result.put("action", "order");
                }else if ("3".equals(dto.get("mes"))) {

                    result.put("mes", selectOrder(LoginServe.tokens.get(dto.get("token")))
                            + "\n" +  initIndex());
                    result.put("token", dto.get("token"));
                    result.put("action", "index");
                }else {
                    result.put("mes", "输入不合法！"
                            +"\n"
                            + initIndex());
                    result.put("token", dto.get("token"));
                    result.put("action", "index");
                }
            } else if ("order".equals(dto.get("action"))) {
                check(dto.get("token"));
                String s = createOrder(dto.get("mes"), LoginServe.tokens.get(dto.get("token")));
                result.put("mes", s
                        +"\n"
                        + initIndex());
                result.put("token", dto.get("token"));
                result.put("action", "index");
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("系统发生异常，请重新登录。");
            result.put("mes", "请重新登录。");
            result.put("action", "login");
        }


        return result;
    }

    private String selectOrder(String userName) {
        StringBuilder sb = new StringBuilder();
        sb.append(userName + "，你的订餐信息如下：\n");
        List<ScOrder> list = null;
        if (LoginServe.orders.containsKey(userName)) {
            list = LoginServe.orders.get(userName);
            if (list.size() > 0) {
                for (ScOrder po : list) {
                    sb.append("订单编号：" + po.getNo() + ",");
                    sb.append("菜品：" + po.getName() + ",");
                    sb.append("数量：" + po.getCount() + ",");
                    sb.append("金额：" + po.getTotalPrice() + "。");
                    sb.append("\n");
                }

            } else {
                sb.append("无\n");
            }
        } else {
            sb.append("无\n");
        }
        sb.append("==========================");
        return sb.toString();
    }

    private String createOrder(String mes, String userName) {
        String result = "";
        try {
            String[] arr = mes.split(",");
            int no = new Integer(arr[0].trim());
            int count = new Integer(arr[1].trim());
            ScOrder o = new ScOrder();
            o.setNo(LoginServe.initId());
            o.setDishNo(no);
            o.setCount(count);
            //拿到菜品信息
            List<ScDish> l = LoginServe.dishes;
            ScDish scd = null;
            for (ScDish dto : l) {
                if (dto.getNo() == no) {
                    scd = dto;
                }
            }

            o.setName(scd.getName());
            o.setTotalPrice(count * scd.getPrice());
            o.setUserName(userName);

            List<ScOrder> list = null;
            if (LoginServe.orders.containsKey(userName)) {
                list = LoginServe.orders.get(userName);
            } else {
                list = new ArrayList<>();
                LoginServe.orders.put(userName, list);
            }
            list.add(o);
            result = "下单成功。";
        } catch (Exception e) {
            result = "输入数据有误，下单失败";
        }
        return result;
    }

    private String initOrder() {
        List<ScDish> l = LoginServe.dishes;
        StringBuffer sb = new StringBuffer();
        sb.append("编号\t菜名\t单价\n");
        for (ScDish d : l) {
            sb.append(d.getNo() + "\t" + d.getName()
                    + "\t" + d.getPrice() + "元\n");
        }
        sb.append("请输入菜品编号和点餐数量，中间用英文逗号隔开：");
        return sb.toString();
    }

    private void check(String token) throws Exception {
        if (token == null || token.length() == 0) {
            throw new Exception("验证登录失败");
        } else {
            if (LoginServe.tokens.containsKey(token)) {

            } else {
                throw new Exception("验证登录失败");
            }
        }
    }

    private String initIndex() {
        StringBuffer sb = new StringBuffer();
        sb.append("1、查看个人信息\n" +
                "2、点餐\n" +
                "3、查看订餐信息\n" +
                "0、退出\n" +
                "（输入选项前的数字，执行相关功能）");
        return sb.toString();
    }
}
